<?php

/*
 * 供应商相关相关类
*
*/
class VendorAction extends Action {
	/**
	 * 获取供应商列表数据
	 * Enter description here ...
	 * @param unknown_type $start
	 * @param unknown_type $limit
	 * @param string $type  商家类型：supply供应商，channel:渠道商,both:既是供应商又是渠道商
	 */
	public function getList($start=0,$limit=25,$order="a.updateTime",$orderBy="desc",$name='',$status='',$agentName=null,$isExport=false,$type='',$vid='') {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
        $cuid = Session::$user['id'];
		Session::switchCustomer(0);
		$VendorModel = M("mivendor");
        $customerUser = M("customer_user");
		$where['a.deleted']=array('eq',0);
		$where['a.cId']=array('eq',$customerId);
//		$where["b.customerId"] = array("eq",$customerId);
//		$where["b.agent"] = array("eq","vendor");
		isset($name)&&$name?$where['a.name']=array('like','%'.$name.'%'):'';
        isset($agentName)&&$agentName?$where['c.name']=array('like','%'.$agentName.'%'):'';
		$status!=''?$where['a.status']=$status:'';
		//添加供应商、渠道商类型筛选
		if($type == 'supply') {
		    $where['a.isSupplyVendor'] = 1;
        }else if ($type == 'channel') {
            $where['a.isChannelVendor'] = 1;
        }else if ($type == 'both'){
            $where['a.isSupplyVendor'] = 1;
            $where['a.isChannelVendor'] = 1;
        }
        //mh添加于20180620，用于渠道商家查询
        if ($vid) {
            $vids = R("Vendor/getMivendorChildList",array($vid,'string'));
            $where['a.id'] = array('IN', $vids);
        }else {
            if (Session::isVendor()){
                $userVid = $customerUser->where("id=$cuid")->getField('vid');
                //mh修改于20180620，用户渠道体系升级，改用in查询
                $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                $where['a.id'] = array('IN', $vids);
            }
        }

		Session::switchCustomer($customerId);
        if($isExport){
            $result = $VendorModel->alias('a')
                ->join("left join wx_customer_user b on a.fromCustomerUserId=b.id and b.agent ='vendor' and  b.customerId =".$customerId)
                ->join("wx_vendor_agent c on a.vendorAgent=c.id")
                ->join("wx_mivendor d on a.pid=d.id")
                ->field("a.*,b.loginName,c.name as agentName,d.name as pname")
                ->where($where)
                ->order("$order $orderBy")
                ->select();
            foreach($result as $key=>$value){
                $newArr[$key]['name']=$value['name'];
                $newArr[$key]['totalRevenue']=$value['totalRevenue'];
                $newArr[$key]['balance']=$value['balance'];
                $newArr[$key]['totalTixian']=$value['totalTixian'];
                if($value['certificationType']){
                    $newArr[$key]['certificationType']='个人认证';
                }else{
                    $newArr[$key]['certificationType']='企业认证';
                }
                $newArr[$key]['province']=$value['province'];
                $newArr[$key]['city']=$value['city'];
                $newArr[$key]['country']=$value['country'];
                $newArr[$key]['address']=$value['address'];
                $newArr[$key]['phone']=$value['phone'];
                $newArr[$key]['contact']=$value['contact'];
                $newArr[$key]['longitude']=$value['longitude'];
                $newArr[$key]['latitude']=$value['latitude'];
                if($value['isPickUp']){
                    $newArr[$key]['isPickUp']='是';
                }else{
                    $newArr[$key]['isPickUp']='否';
                }
                $newArr[$key]['wxid']=$value['wxid'];
                $newArr[$key]['IDName']=$value['IDName'];
                $newArr[$key]['companyName']=$value['companyName'];
                $newArr[$key]['phone']=$value['phone'];
                $newArr[$key]['serialNumber']=$value['serialNumber'];
                $newArr[$key]['province']=$value['province'];
                $newArr[$key]['city']=$value['city'];
                if($value['status']==1||$value['status']==2){
                    $newArr[$key]['status']='待审核';
                }else if($value['status']==3){
                    $newArr[$key]['status']='已审核';
                }else if($value['status']==4){
                    $newArr[$key]['status']='已过期';
                }else if($value['status']==5){
                    $newArr[$key]['status']='审核失败';
                }else{
                    $newArr[$key]['status']='未提交';
                }
                $newArr[$key]['createTime']=$value['createTime'];
            }

            $expCellName  = array(
                array('name','商家名称'),
                array('totalRevenue','累计收入'),
                array('balance','余额'),
                array('totalTixian','累计提现'),
                array('certificationType','认证类型'),
                array('wxid','微信号'),
                array('IDName','身份证姓名'),
                array('companyName','公司名称'),
                array('phone','电话'),
                array('serialNumber','公司编号'),
                array('province','省'),
                array('city','市'),
                array('status','状态'),
                array('createTime','注册时间')
            );
            Output::instance()->objArrayExcel('商家信息', $expCellName, $newArr);
        }else{
        	//孟慧20180205更改此处，不需要在此处获取后台登陆人员信息.[注释处]
            $result = $VendorModel->alias('a')
                //->join("left join wx_customer_user b on a.fromCustomerUserId=b.id and b.agent ='vendor' and  b.customerId =".$customerId)
                ->join("wx_vendor_agent c on a.vendorAgent=c.id")
                ->join("wx_mivendor d on a.pid=d.id")
                //->field("a.*,b.loginName,c.name as agentName")
                ->field("a.*,c.name as agentName,d.name as pname")
                ->where($where)
                ->order("$order $orderBy")
                ->limit($start, $limit)->select();
              foreach($result as $key=>$value){
	              	$result[$key]['totalRevenue'] = round($value['totalRevenue'],2);
	              	$result[$key]['balance'] = round($value['balance'],2);     
              	}
            if ($result) {
                $count = $VendorModel->alias('a')
                    //->join("left join wx_customer_user b on a.fromCustomerUserId=b.id and b.agent ='vendor' and  b.customerId =".$customerId)
                    ->join("wx_vendor_agent c on a.vendorAgent=c.id")
                    ->where($where)
                    ->order("$order $orderBy")
                    ->count();
                Output::instance()->objArray($result,$count);
            } else {
				$return['code'] = 0;
				$return['msg'] = 'ok';
				$return['results'] = [];
				$return['total'] = 0;
                Output::instance()->object($return);
            }
        }
	}
	/**
	 * 供应商保存方法
	 * @param $id
	 * @param $mId 		/商城id
	 * @param $logo 	/供应商logo
	 * @param $name		/供应商名称
	 * @param $loginName
	 * @param $password
	 * @param null $canLogin
	 * @param null $companyName
	 * @param null $serialNumber	/公司编号
	 * @param null $busLicence		/营业执照
	 * @param null $IDPositive
	 * @param null $IDBack
	 * @param int $certificationType	/企业认证还是个人认证
	 * @param null $phone
	 * @param null $wxid
	 * @param null $status
	 * @param null $message		/认证信息
	 * @param null $province	/省
	 * @param null $city		/市
	 * @param null $areaCode		/区号
	 * @param null $supplierModule		/接口模式
	 * @param null $authConfig		/authConfig
	 * @param int $isSynchro		/是否自动同步0:不自动,1:自动同步
	 * @param int $depotRevenueSetting		仓储收益设置
	 * @param int $settlementTimeType		结算时间类型【anytime：随时结算。week:按周结算，month：按月结算。】
	 * @param int $settlementTimeSetting		结算时间设置
	 * @param int $isSupplyVendor    是否是供应商(1:是，0：不是)
	 * @param int $isChannelVendor		是否是渠道商（1：是，0：不是）
	 * @param string $area		/区
	 */
	public function save($id=null,$mId=null,$logo=null,$name,$loginName=null,$password=null,$canLogin=null,$companyName=null,$serialNumber=null,$busLicence=null,
		$IDPositive=null,$IDBack=null,$certificationType=0,$phone=null,$wxid=null,$status=null,$message=null,$province=null,$city=null,
		$areaCode=null,$supplierModule=null,$authConfig=null, $isSynchro=0,$depotRevenueSetting,$settlementTimeType,$settlementTimeSetting,$isSupplyVendor,$isChannelVendor,$pid=0,$area=''){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$customerUserModel=M("customer_user");
		$VendorModel = M("mivendor");
		if($serialNumber&&$certificationType!=1){
		    if($id){
                $oldSerialNumber = $VendorModel->where("id=$id")->getField("serialNumber");
                if($oldSerialNumber!=$serialNumber){
                    $serialNumberResult = $VendorModel->where("serialNumber=$serialNumber and deleted=0 and cId=$customerId")->find();
                    if($serialNumberResult){
                        Output::instance()->resultCode(1,"公司编号重复");
                        return;
                    }
                }
            }else{
                $serialNumberResult = $VendorModel->where("serialNumber=$serialNumber and deleted=0 and cId=$customerId")->find();
                if($serialNumberResult){
                    Output::instance()->resultCode(1,"公司编号重复");
                    return;
                }
            }

		}else if($certificationType!=1){
            while(strlen($areaCode)<4){
                $areaCode='0'.$areaCode;
            };
            $code = $VendorModel->where("cId=$customerId and areaCode='$areaCode'")->field("max(serialNumber) as serialNumber")->find();
            if($code){
                $code = substr($code['serialNumber'],-4);
                $code +=1;
            }else{
                $code = 1;
            }
            while(strlen($code)<4){
                $code='0'.$code;
            };
            $serialNumber= $areaCode.$code;
            do{
                $isrepeat= $VendorModel->where("cId=$customerId and serialNumber='$serialNumber'")->find();
                if($isrepeat){
                    $code+=1;
                    while(strlen($code)<4){
                        $code='0'.$code;
                    };
                    $serialNumber= $areaCode.$code;
                }
            }while($isrepeat);
        }
        //这是之前的已添加可登陆后台逻辑，孟慧20180205删掉此逻辑
		// if($canLogin){
		// 	$userResult = $VendorModel->where("id=$id")->getField("fromCustomerUserId");
		// 	$where['loginName']=array("eq",$loginName);
		// 	$where['status']=array("eq","open");
		// 	$where['id']=array("neq",$userResult);
		// 	$res=$customerUserModel->where($where)->find();
		// 	if($res && count($res) > 0) {
		// 		Output::instance()->resultCode('1','登录名已经存在！');
		// 		return;
		// 	}
		// 	$userData["loginName"]=$loginName;
		// 	$data["mId"]=0;
		// 	if($password) {
		// 		$userData["password"]=Encryption::password($password);
		// 	}
		// 	$userData["status"] = 'open';
		// 	$userData["agent"]="vendor";
		// 	if($userResult) {
		// 		$customerUserModel->where("id=" . $userResult)->save($userData);
		// 	} else {
		// 		$userData["customerId"]=$customerId;
		// 		$userResult=$customerUserModel->add($userData);

		// 	}
		// }else{
		// 	$customerUserId = $VendorModel->alias("a")
		// 		->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
		// 		->where("a.id=$id")
		// 		->getField("b.id");
		// 	$customerUserModel->where("id=$customerUserId")->setField("status","close");
		// 	$data['fromCustomerUserId']=null;
		// }
		//$data["fromCustomerUserId"]=$userResult;----
		$data["name"]=$name;
		$data["logo"]=$logo;
		$data['companyName']=$companyName;
		$data['serialNumber']=$serialNumber;
		$data['busLicence']=$busLicence;
		$data['IDPositive']=$IDPositive;
		$data['IDBack']=$IDBack;
		$data['certificaImgUrl']=null;
		$data['certificationType']=$certificationType;
		$data['phone']=$phone;
		$data['wxid']=$wxid;
		$data['Message']=$message;
		if($status){
			$data['status']=$status;
			$oldStatus = $VendorModel->where("id=$id")->getField("status");
			if($oldStatus!=$status&&$status==3){
				$data['certificaTime']=date("Y-m-d H:i:s");
			}
		}
		$data["deleted"]=0;
		$data["updateTime"]=date("Y-m-d H:i:s");
		$data["cId"]=$customerId;
		$data['province']=$province;
        $data['city']=$city;
		$data['supplierModule'] = $supplierModule;
		$data['authConfig']=$authConfig;
		/*新增两个参数是否同步订单,jie*/
        $data['isSynchro']=$isSynchro;
		$data['depotRevenueSetting']=$depotRevenueSetting;
		$data['settlementTimeType']=$settlementTimeType;
		$data['settlementTimeSetting']=$settlementTimeSetting;
		$data['isSupplyVendor']=$isSupplyVendor;
		$data['isChannelVendor']=$isChannelVendor;
		$data['pid']=$pid;
		$data['area']=$area;
		/*$data['synchroUrl']=$synchroUrl;*/
		if($id) {
			if ($id == $pid){
				$return['code'] = 1;
	            $return['msg'] = '不能设置自己为上级商家';
	            Output::instance()->object($return);
	            exit();
			}
			$result=$VendorModel->where("id=$id")->save($data);
		} else {
			$data["createTime"]=date("Y-m-d H:i:s");
			$result=$VendorModel->add($data);
			$idReturn = $result;
		}
		if ($result!==false) {
			if ($id) {
				R('Log/add', array('newMivendor', module_id_newMivendor, '商家管理', op_update, $VendorModel->getLastSql(), '修改商家信息：' . $name));
			}else{
				R('Log/add', array('newMivendor', module_id_newMivendor, '商家管理', op_add, $VendorModel->getLastSql(), '添加商家：' . $name));
			}
   			 
			$return['code'] = 0;
            $return['msg'] = 'ok';
            $return['id'] = $idReturn;
            Output::instance()->object($return);

		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		Session::switchCustomer($customerId);
	}
	/*修改获取单条*/
	public function getVendorById($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);

		$VenderModel = M("mivendor");
		//孟慧20180205更改此处，不需要在此处获取后台登陆人员信息
		 $where["a.id"]=$id;
		 $result=$VenderModel->alias('a')->join("wx_mivendor b on a.pid=b.id")
		 ->field("a.*,b.name as pname")
		 ->where($where)->find();
		//$result=$VenderModel->where("id=$id")->find();
		Session::switchCustomer($customerId);
		if ($result) {
			if($result['authConfig']){
				$authConfig = json_decode($result['authConfig'],true);
				$result = array_merge($result,$authConfig);
			}
			Output::instance()->object($result);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	/*删除供应商*/
	public function delete($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
				
		$VenderModel = M("mivendor");
		
		$where["id"]=$id;
		$data["deleted"] =1;
		$data['updateTime']=date("Y-m-d H:i:s");
		$result=$VenderModel->where($where)->save($data);
		$name = $VenderModel->where($where)->getField('name');
		if ($result) {
			R('Log/add', array('newMivendor', module_id_newMivendor, '商家', op_delete, $VenderModel->getLastSql(), '删除商家' . $name));
			Output::instance()->object(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
		Session::switchCustomer($customerId);
	}
	//分销商品列表
	public function distributionList($name='',$start=0,$limit=10){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$distribution = M("module_product_distribution");
		$productTag = M("module_product_tag");
		Session::switchCustomer($customerId);
		$condition["cId"] = $customerId;
		$condition["name"]=array('like',"%".$name."%");
		$condition["deleted"] = 0;
		$result = $distribution->where($condition)->limit($start,$limit)->select();
		foreach($result as $key=>$value){
			if($value["tagId"]){
				$where["id"] = array("in",$value["tagId"]);
				$tagInfo = $productTag->where($where)->field("group_concat(name) as tagName")->find();
				$result[$key]["tagName"] = $tagInfo["tagName"];
			}else{
				$result[$key]["tagName"] = null;
			}
		}
		if ($result) {
			$count = $distribution->where($condition)->count();
			Output::instance()->objArray($result,$count);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//分销详情
	public function getDistributionById($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$distribution = M("module_product_distribution");
		$productTag = M("module_product_tag");
		Session::switchCustomer($customerId);
		$condition["id"] = $id;
		$result = $distribution->alias("a")->where($condition)->find();
		if($result["tagId"]){
			$where["id"] = array("in",$result["tagId"]);
			$tagInfo = $productTag->where($where)->field("group_concat(name) as tagName")->find();
			$result["tagName"] = $tagInfo["tagName"];
		}else{
			$result["tagName"] = null;
		}
		if ($result) {
			Output::instance()->object($result);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//保存分销商品
	public function saveDistribution($name,$tagId,$logo=null,$id=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$distribution = M("module_product_distribution");
		Session::switchCustomer($customerId);
		$data["name"] = $name;
		$data["tagId"] = $tagId;
		$data["logo"] = $logo;
		if($id){
			$data["id"] = $id;
			$result = $distribution->save($data);
		}else{
			$data["cId"] = $customerId;
			$result = $distribution->add($data);
		}
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//删除分销商品标签
	public static function distributionDelete($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$distribution = M("module_product_distribution");
		Session::switchCustomer($customerId);
		$data["deleted"] = 1;
		$data["updateTime"] = date("Y-m-d H:i:s");
		$result = $distribution->where("id=$id")->save($data);
		if($result){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//获得商城对于供应商的设置
	public function getVendorConfig(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$vendorConfig = M("vendor_config");
		$productModel = M("module_product");
		Session::switchCustomer($customerId);
		$result = $vendorConfig->alias("a")
			->join("wx_module_product b on a.auditCost=b.id")
			->where("a.cid=$customerId")->field("a.*,b.name as auditProName")->find();
		if($result){
			$result['menuJson'] = json_decode($result['menuJson'],true);
			$result['menuJson']['wx']['menu'] = json_decode($result['menuJson']['wx']['menu'],true);
			$result['menuJson']['app']['menu'] = json_decode($result['menuJson']['app']['menu'],true);
			$result['registerPic'] = json_decode($result['registerPic'],true);
			foreach($result['registerPic'] as $key=>$value){
				$result['registerPic'][$key]['url']=$value['picUrl'];
			}
			if($result['certificateConfig']){
				$certificateConfig = json_decode($result['certificateConfig'],true);
				$result = array_merge($result,$certificateConfig);
			}
			$productList = $productModel->where("id in (".$result['defaultPid'].")")->field("id,name")->select();
			$result['proList']=$productList;
			Output::instance()->object($result);
		}else{
			Output::instance()->resultCode();
		}
	}
	//保存商城对于供应商的设置
	public function saveVendorConfig($registerRequired=null,$systemName=null,$registerPic=null,$agreementName=null,$overdueDay=null,
			$agreement=null,$experienceAllowed=null,$auditRequired=null,$auditCost=null,$defaultPid=null,$limitedProductNum=null,
			$auditedStoreNum=null,$limitedStroeNum=null,$auditedProductNum=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$vendorConfig = M("vendor_config");
		Session::switchCustomer($customerId);
		$id  = $vendorConfig->where("cid=$customerId")->getField("id");
		$data['registerRequired']=$registerRequired;
		$data['systemName']=$systemName;
		$data['registerPic']=$registerPic;
		$data['agreementName']=$agreementName;
		$data['agreement']=$agreement;
		$data['experienceAllowed']=$experienceAllowed;
		$data['auditRequired']=$auditRequired;
		$data['auditCost']=$auditCost;
		$data['defaultPid']=$defaultPid;
		$data['limitedProductNum']=$limitedProductNum;
		$data['auditedStoreNum']=$auditedStoreNum;
		$data['limitedStroeNum']=$limitedStroeNum;
		$data['auditedProductNum']=$auditedProductNum;
		$data['overdueDay']=$overdueDay;
		if($id){
			$result = $vendorConfig->where("id=$id")->save($data);
		}else{
			$data['cid']=$customerId;
			$data['createTime']=date("Y-m-d H:i:s");
			$result = $vendorConfig->add($data);
		}
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//界面配置保存
	public function saveVendorStyleConfig($menuConfig=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$vendorConfig = M("vendor_config");
		Session::switchCustomer($customerId);
		$id  = $vendorConfig->where("cid=$customerId")->getField("id");
		$data['menuJson'] = $menuConfig;
		if($id){
			$result = $vendorConfig->where("id=$id")->save($data);
		}else{
			$data['cid']=$customerId;
			$data['createTime']=date("Y-m-d H:i:s");
			$result = $vendorConfig->add($data);
		}
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//证书配置保存
	public function saveVendorCertConfig($certificateBackground=null,$certificateConfig=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$vendorConfig = M("vendor_config");
		$vendorModel = M("mivendor");
		Session::switchCustomer($customerId);
		$vendorInfo  = $vendorConfig->where("cid=$customerId")->find();
		$data['certificateBackground']=$certificateBackground;
		$data['certificateConfig']=$certificateConfig;
		if($vendorInfo){
			if($vendorInfo['certificateBackground']!=$certificateBackground||$vendorInfo['certificateConfig']!=$certificateConfig){
				$vendorModel->where("certificaImgUrl is not null")->setField("certificaImgUrl");
			}

			$result = $vendorConfig->where("id=".$vendorInfo['id'])->save($data);
		}else{
			$data['cid']=$customerId;
			$data['createTime']=date("Y-m-d H:i:s");
			$result = $vendorConfig->add($data);
		}
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}

	//小程序供应商支付方式设置
	public function vendorPayConfig(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerSuperSettingModel = D('customer_super_setting');
		$condition['customerId'] = array('eq', $customerId);
		$setting = $CustomerSuperSettingModel->where($condition)
			->field("allowWXPay, allowTransfer, allowUPay,allowTenPay, allowDeliveryPay, allowStored,allowAliPay")->find();

		$PayTypeModel = M('vendor_app_pay_type');
		Session::switchCustomer($customerId);
		if (!$setting) {
			Output::instance()->resultCode(code_product_paytype_invalid);
			return;
		}

		$payType = $PayTypeModel->field("payTypeText, payTypeValue, isDefault")->select();
		if ($payType === false) {
			Output::instance()->resultCode(code_sql_error);
			Log::write($PayTypeModel->getLastSql());
			return;
		}

		$payTypeArr = array();
		$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_WXPAY_TEXT, ORDER_PAYTYPE_WXPAY);
		array_push($payTypeArr, $data);
		$data = $this->addPayTypeToArr($payType, "支付宝", "alipay");
		array_push($payTypeArr, $data);
		$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_TRANSFER_TEXT, ORDER_PAYTYPE_TRANSFER);
		array_push($payTypeArr, $data);
		$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_DELIVERIY_PAY_TEXT, ORDER_PAYTYPE_DELIVERIY_PAY);
		array_push($payTypeArr, $data);
		$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_STORED_PAY_TEXT, ORDER_PAYTYPE_STORED_PAY);
		array_push($payTypeArr, $data);
		$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_UPAY_TEXT, ORDER_PAYTYPE_UPAY);
		array_push($payTypeArr, $data);
		$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_TENPAY_TEXT, ORDER_PAYTYPE_TENPAY);
		array_push($payTypeArr, $data);
		$result["payType"] = $payTypeArr;
// 		$result["wxpay"] = $this->getWxPay();
		Output::instance()->object($result);

	}
	private function addPayTypeToArr($searchArr, $payTypeText, $payTypeValue) {
		foreach ($searchArr as $temp) {
			if ($temp["payTypeValue"] == $payTypeValue) {
				$temp["isChecked"] = 1;
				return $temp;
			}
		}
		$tempNone["payTypeText"] = $payTypeText;
		$tempNone["payTypeValue"] = $payTypeValue;
		$tempNone["isDefault"] = 0;
		$tempNone["isChecked"] = 0;
		return $tempNone;
	}
	//保存支付方式
	public function saveAppPayType($supportWxpay = 0, $supportDelivery = 0, $supportStored = 0,
									  $supportTransfer = 0, $supportUpay = 0,$supportAlipay = 0,$supportTenpay = 0, $default = '') {
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}

			$customerId = Session::$user["customerId"];
			Session::switchCustomer(0);

			$CustomerSuperSettingModel = D('customer_super_setting');
			$condition['customerId'] = array('eq', $customerId);
			$setting = $CustomerSuperSettingModel->where($condition)
				->field("allowWXPay, allowTransfer, allowUPay,allowTenPay, allowDeliveryPay, allowStored,allowAliPay")->find();

			Session::switchCustomer($customerId);
			if (!$setting) {
				Output::instance()->resultCode(code_product_paytype_invalid);
				return;
			}

			if ((empty($setting["allowWXPay"]) && $supportWxpay)
				|| (empty($setting["allowTransfer"]) && $supportTransfer)
				|| (empty($setting["allowUPay"]) && $supportUpay)
				|| (empty($setting["allowTenPay"]) && $supportTenpay)
				|| (empty($setting["allowDeliveryPay"]) && $supportDelivery)
				|| (empty($setting["allowStored"]) && $supportStored)
				|| (empty($setting["allowAliPay"]) && $supportAlipay) ) {
				Output::instance()->resultCode(code_product_paytype_no_right);
				return;
			}

			$result = $this->setPayType($supportWxpay, $supportDelivery, $supportStored,
				$supportTransfer, $supportUpay,$supportTenpay, $supportAlipay,$default);
			if($result === false){
				return;
			}

			Output::instance()->resultCode();
		}
		private function setPayType($supportWxpay, $supportDelivery, $supportStored,
									$supportTransfer, $supportUpay,$supportTenpay, $supportAlipay,$default) {
			$customerId = Session::$user["customerId"];
			Session::switchCustomer(0);
			$PayTypeModel = M('vendor_app_pay_type');
			Session::switchCustomer($customerId);
			$dataArr = array();
			if ($supportAlipay) {
				$data = array();
				$data["payTypeText"] = ORDER_PAYTYPE_ALIPAY_TEXT;
				$data["payTypeValue"] = ORDER_PAYTYPE_ALIPAY;
				$data["cid"] = $customerId;
				if ($default == ORDER_PAYTYPE_ALIPAY) {
					$data["isDefault"] = 1;
				} else {
					$data["isDefault"] = 0;
				}
				array_push($dataArr, $data);
			}
			if ($supportWxpay) {
				$data = array();
				$data["payTypeText"] = ORDER_PAYTYPE_WXPAY_TEXT;
				$data["payTypeValue"] = ORDER_PAYTYPE_WXPAY;
				$data["cid"] = $customerId;
				if ($default == ORDER_PAYTYPE_WXPAY) {
					$data["isDefault"] = 1;
				} else {
					$data["isDefault"] = 0;
				}
				array_push($dataArr, $data);
			}
			if ($supportDelivery) {
				$data = array();
				$data["payTypeText"] = ORDER_PAYTYPE_DELIVERIY_PAY_TEXT;
				$data["payTypeValue"] = ORDER_PAYTYPE_DELIVERIY_PAY;
				$data["cid"] = $customerId;
				if ($default == ORDER_PAYTYPE_DELIVERIY_PAY) {
					$data["isDefault"] = 1;
				}else {
					$data["isDefault"] = 0;
				}
				array_push($dataArr, $data);
			}
			if ($supportStored) {
				$data = array();
				$data["payTypeText"] = ORDER_PAYTYPE_STORED_PAY_TEXT;
				$data["payTypeValue"] = ORDER_PAYTYPE_STORED_PAY;
				$data["cid"] = $customerId;
				if ($default == ORDER_PAYTYPE_STORED_PAY) {
					$data["isDefault"] = 1;
				}else {
					$data["isDefault"] = 0;
				}
				array_push($dataArr, $data);
			}
			if ($supportTransfer) {
				$data = array();
				$data["payTypeText"] = ORDER_PAYTYPE_TRANSFER_TEXT;
				$data["payTypeValue"] = ORDER_PAYTYPE_TRANSFER;
				$data["cid"] = $customerId;
				if ($default == ORDER_PAYTYPE_TRANSFER) {
					$data["isDefault"] = 1;
				}else {
					$data["isDefault"] = 0;
				}
				array_push($dataArr, $data);
			}
			if ($supportUpay) {
				$data = array();
				$data["payTypeText"] = ORDER_PAYTYPE_UPAY_TEXT;
				$data["payTypeValue"] = ORDER_PAYTYPE_UPAY;
				$data["cid"] = $customerId;
				if ($default == ORDER_PAYTYPE_UPAY) {
					$data["isDefault"] = 1;
				}else {
					$data["isDefault"] = 0;
				}
				array_push($dataArr, $data);
			}


			if ($supportTenpay) {
				$data = array();
				$data["payTypeText"] = ORDER_PAYTYPE_TENPAY_TEXT;
				$data["payTypeValue"] = ORDER_PAYTYPE_TENPAY;
				$data["cid"] = $customerId;
				if ($default == ORDER_PAYTYPE_TENPAY) {
					$data["isDefault"] = 1;
				}else {
					$data["isDefault"] = 0;
				}
				array_push($dataArr, $data);
			}
			if (count($dataArr) > 0) {
				$PayTypeModel->execute('truncate table __TABLE__');
				$result = $PayTypeModel->addAll($dataArr);
				if (!$result) {
					Log::write($PayTypeModel->getDbError());
					Output::instance()->resultCode(code_sql_error);
					return false;
				}
			}
			return true;
		}
		public static function recharge($id,$payment,$recharge){
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
            $customerId = Session::$user["customerId"];
            Session::switchCustomer(0);
            $mivendorModel = M('mivendor');
            $agentModel = M("vendor_agent");
            $vendorAccount = M("account_vendor");
            $agentAccount = M("account_agent");
            Session::switchCustomer($customerId);
            $agentInfo = $mivendorModel->alias("a")
                ->join("inner join wx_vendor_agent b on a.vendorAgent=b.id")
                ->where("a.id=$id")
                ->field("b.*,a.name as vendorName")->find();
            $mivendorModel->startTrans();
            $data['module'] = "recharge";
            $data['vId'] = $id;
            $data['description'] = "充值".$recharge."元";
            $data['money'] = $recharge;
            $data['type'] = 0;
            $data['deleted'] = 0;
            $data['createTime'] = date("Y-m-d H:i:s");
            $result = $vendorAccount->add($data);
            $moduleId=$result;
            if(!$result){
                $mivendorModel->rollback();
                return;
            }
            $result = $mivendorModel->where("id=$id")->setInc("balance",$recharge);
            if($result===false){
                $mivendorModel->rollback();
                return;
            }
            $result = $mivendorModel->where("id=$id")->setInc("totalRevenue",$recharge);
            if($result===false){
                $mivendorModel->rollback();
                return;
            }
            if($agentInfo&&$agentInfo['rechargeAward']>0){
                $money = $payment*$agentInfo['rechargeAward'];
                $data['module'] = "vendor";
                $data["moduleId"]=$moduleId;
                $data['agentId'] = $agentInfo['id'];
                $data['description'] = "商家".$agentInfo['vendorName']."充值";
                $data['money'] = $money;
                $data['type'] = 0;
                $data['deleted'] = 0;
                $data['createTime'] = date("Y-m-d H:i:s");
                $result = $agentAccount->add($data);
                if(!$result){
                    $mivendorModel->rollback();
                    return;
                }
                $result = $agentModel->where("id=".$agentInfo['id'])->setInc("balance",$money);
                if($result===false){
                    $mivendorModel->rollback();
                    return;
                }
                $result = $agentModel->where("id=".$agentInfo['id'])->setInc("totalRevenue",$money);
                if($result===false){
                    $mivendorModel->rollback();
                    return;
                }
            }
            $mivendorModel->commit();
            Output::instance()->resultCode();
        }
        //流量
        public static function getVendorVisit($id,$start=0,$limit=10){
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
            $customerId = Session::$user["customerId"];
            Session::switchCustomer($customerId);
            $vendorVisit = M('vendor_visit_log');
            $arr = $vendorVisit->alias("a")
                ->join("wx_".$customerId."_user_weixin_info b on a.userId=b.userId")
                ->where("a.vid=$id")
                ->field("a.id,a.keywords,a.descrition,a.createTime,a.url,b.nickname,b.headimgurl")
                ->order("a.createTime desc")
                ->limit($start,$limit)
                ->select();
            if($arr){
                $count= $vendorVisit->alias("a")
                    ->join("wx_".$customerId."_user_weixin_info b on a.userId=b.userId")
                    ->where("a.vid=$id")
                    ->count();
                Output::instance()->objArray($arr,$count);
            }else{
                Output::instance()->resultCode();
            }
        }
        //商家二维码
        public function getStoreCode($id,$start=0,$limit=10){
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
            $customerId = Session::$user["customerId"];
            Session::switchCustomer(0);
            $storeModel = M("store");
            Session::switchCustomer($customerId);
            $where["a.vId"]=array("eq",$id);
            $where["a.deleted"]=array("eq",0);
            $arr = $storeModel->alias("a")
                ->join("inner join wx_vendor_qrcode b on a.id=b.storeId")
                ->where($where)
                ->field("b.*")
                ->limit($start,$limit)->order("b.activateTime desc")->select();
            if($arr){
                $count  = $storeModel->alias("a")
                    ->join("inner join wx_store_qrcode b on a.id=b.storeId")
                    ->where($where)->count();
                Output::instance()->objArray($arr,$count);
            }else{
                Output::instance()->resultCode();
            }

        }
        public function newStoreCode($id){
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
            $customerId = Session::$user["customerId"];
            Session::switchCustomer(0);
            $storeModel = M("store");
            $codeConfig = M("vendor_config");
            $codeExport = M("vendor_qrcode_export");
            $storeCode = M("vendor_qrcode");
            Session::switchCustomer($customerId);
            $storeId = $storeModel->where("vId=$id and deleted=0")->getField("id");
            $configInfo = $codeConfig->where("cid=$customerId")->find();
            $qrcodeData['cid']=$customerId;
            $qrcodeData['storeId']=$storeId;
            $qrcodeData['vId']=$id;
            $qrcodeData['createTime']=date("Y-m-d H:i:s");
            $qrcodeData['activateTime']=date("Y-m-d H:i:s");
            $qrcodeId = $storeCode->add($qrcodeData);
            $data = WeixinApi::createwxaqrcode("page/vendorIndex/vendorIndex?id=$id","qrcode".date("His").$qrcodeId.".jpg");
            $qrImg = $data->path;
            $storeCode->where("id=$qrcodeId")->setField("qrcodeUrl",$qrImg);
            $path=LOCAL_PIC_PATH . "storeCode/";
            $fileName = date("His").$qrcodeId;
            R("Coupon/createImage",array($path,$fileName,$qrImg,$configInfo['qrcodeBack'],$configInfo['qrcodeLocation'],$configInfo['qrcodeSize']));
            $fileName=$path.$fileName.".png";
            $result = R("Upload/uploadLocalFileToOss",array($fileName,$fileName));
            $arr['url']=$result->path;
            if($arr['url']){
                Output::instance()->object($arr);
            }else{
                Output::instance()->resultCode(1,"生成失败");
            }
        }
        //商家优惠券
        public function getVendorCoupon($id,$name=null,$start=0,$limit=10){
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
            $customerId = Session::$user["customerId"];
            Session::switchCustomer(0);
            $couponModel = M("module_coupon");
			$userCoupon = M("module_user_coupon");
            Session::switchCustomer($customerId);
            $where['b.vid']=array("eq",$id);
            $where['b.deleted']=array("eq",0);
            $name?$where["b.name"]=array("like","%$name%"):"";
            $arr =$couponModel->alias("b")
                ->where($where)
                ->field("b.id,b.createTime,b.name,b.recommend,b.copiesNum,b.surplusNum,b.startTime,b.endTime")
                ->limit($start,$limit)
                ->group("b.id")
                ->select();
            if($arr){
                foreach($arr as $key=>$value){
					$arr[$key]['partakeCount'] = $userCoupon->where("couponId=".$value['id']." and status=0")->count();
					$arr[$key]['usedCount'] = $userCoupon->where("couponId=".$value['id']." and status=1")->count();
                    $arr[$key]['startTimeFormat'] = date("Y-m-d",strtotime($value['startTime']));
                    $arr[$key]['endTimeFormat'] = date("Y-m-d",strtotime($value['endTime']));
                }
                $count = $couponModel->alias("b")
                    ->where($where)
                    ->count();
                Output::instance()->objArray($arr,$count);
            }else{
                Output::instance()->resultCode();
            }


        }

    //数据迁移
    public function mivendorDataMigration()
    {
        set_time_limit(0);
        Session::switchCustomer(0);
        $mivendor = M('mivendor');
        $user = M('customer_user');
        $role = M('customer_user_role');
        //取出所有mivendor中fromCustomerUserId不为空的数据
        $where_mivendor['fromCustomerUserId'] = array("EXP",'IS NOT NULL');
        $where_mivendor['deleted'] = 0;
        $mivendorInfo = $mivendor->field("id,cId,fromCustomerUserId")->where($where_mivendor)->select();
        //进行循环查询处理
        foreach ($mivendorInfo as $key => $value) {
            //通过fromCustomerUserId去customer_user表中进行添加vid
            if ($value['fromCustomerUserId']) {
                $where_user['id'] = $value['fromCustomerUserId'];
				$user->where($where_user)->setField("vid",$value['id']);
            } 
        }


    }
    /*
     * 获取商家以及下级所有信息
     * @param  $rootId 查询商家id
     * @param  $type   查询类型，string为内部调用返回字符串类型，其他类型统一对外抛出数组
     */
    public function getMivendorChildList($rootId,$type='')
    {
        $sql = "select getMivendorChildList($rootId)";
        $mivendorChildList= M()->query($sql);
        if ($type == 'string') {
            return substr($mivendorChildList[0]['getMivendorChildList('.$rootId.')'],2);
        }else{
            $sql2 = "SELECT id,name FROM wx_mivendor WHERE FIND_IN_SET(id, getMivendorChildList($rootId))";
            $arr = M()->query($sql2);
            $result['code'] = 0;
            $result['msg'] = '商家信息返回';
            $result['data'] = $arr;
            output::instance()->object($result);
        }
    }
}